package backtracking;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

/**
 * @Author: 海琳琦
 * @Date: 2022/2/25 20:48
 * https://leetcode-cn.com/problems/combination-sum/
 */
public class CombinationSum {

    static List<List<Integer>> result;
    static LinkedList<Integer> list;

    public static List<List<Integer>> combinationSum(int[] candidates, int target) {
        result = new ArrayList<>();
        list = new LinkedList<>();
        backTracking(candidates, target, 0);
        return result;
    }

    public static void backTracking(int[] candidates, int target, int index) {
        if (target == 0) {
            result.add(new ArrayList<>(list));
            return;
        }
        for (int i = index; i < candidates.length; i++) {
            if (target - candidates[i] < 0) {
                continue;
            }
            list.add(candidates[i]);
            backTracking(candidates, target - candidates[i], i);
            list.removeLast();
        }
    }

    public static void main(String[] args) {
        int[] test = {2, 7,  6, 3,5,1};
        combinationSum(test, 9);
    }
}
